package org.zty.util;



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Array;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.zip.CRC32;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;


public class FileUtil {
	public static final int DIR = 1;
	public static final int FILE = 2;
	public static final int DIR_File = 3;
	private final static Logger log = Logger.getLogger(FileUtil.class);

	/**
	 * 通过http方式保存文件
	 * 
	 * @param siteUrl
	 * @param path
	 * @return
	 */
	public static boolean saveHttpFile(String siteUrl, String path,
			String filePath) {
		HttpClient http = null;
		HttpMethod method = null;
		int code = 0;
		boolean flag = false;
		InputStream is = null;
		OutputStream os = null;
		try {
			method = new GetMethod(siteUrl);
			http = new HttpClient();
			Header header = new Header(
					"User-Agent",
					"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; GOSURF; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2)");
			method.setRequestHeader(header);
			code = http.executeMethod(method);
			if (code / 100 < 4) {
				is = method.getResponseBodyAsStream();
			}
			if (is != null) {
				validatePath(path);
				os = new FileOutputStream(new File(filePath));
				byte[] buf = new byte[2048];
				int i = 0;
				while ((i = is.read(buf)) != -1) {
					os.write(buf, 0, i);
				}
				os.close();
				is.close();
			}
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		} finally {
			method.releaseConnection();
		}
		return flag;
	}

	/**
	 * 验证路径是否存在 如果不存在就进行创建
	 * 
	 * @param flag
	 */
	public static synchronized void validatePath(String path) throws ZException {
		try {
			// 检查绝对路径是否存在
			File f = null;
			// 检查相对路径是否存在
			f = new File(path);
			if (!f.exists() && !f.isDirectory()) {
				f.mkdirs();
			}
		} catch (Exception e) {
			throw new ZException("创建路径失败", e);
		}
	}
	
	/**
	 * 验证文件路径是否存在,不存在则创建路径，
	 * @param path 文件全路径
	 * @throws ZException
	 */
	public static synchronized  void validateFilePath(String filePath) throws ZException {
		try {
			// 检查绝对路径是否存在
				File f = new File(filePath);
				File parent = new File(f.getParent());
				if (!parent.exists() && !parent.isDirectory()) {
					parent.mkdirs();
				}
		} catch (Exception e) {
			throw new ZException("创建路径失败",e);
		}
	}

	/**
	 * 只创建文件路径，去掉文件名
	 * 
	 * @param fileName
	 * @throws ZException
	 */
	public static void createFilePath(String fileName) throws ZException {
		try {
			String temp = "";
			int s = -1;
			s = fileName.lastIndexOf("/");
			if (s == -1) {
				s = fileName.lastIndexOf("\\");
			}
			if (s == -1) {
				return;
			}
			temp = fileName.substring(0, s);
			validatePath(temp);
			temp = "";
		} catch (Exception e) {
			throw new ZException("创建路径失败", e);
		}
	}

	/**
	 * 列表所有文件
	 * 
	 * @param strDir
	 * @return String
	 */
	public static String[] listAllFile(String strDir, boolean isFull) {
		return listAllFile(strDir, null, isFull);
	}

	/**
	 * 列表指定目录中的子目录
	 * 
	 * @param strDir
	 * @param isFull
	 *            true列表所有子目录，false列表第一级目录
	 * @return 目录列表
	 * @since v2.0
	 */
	public static String[] listAllSubDir(String strDir, boolean isFull) {
		return listAllFile(strDir, null, isFull, DIR);
	}

	public static String[] listAllFileWithSrcFolder(String strDir,
			String dirName) {
		String[] a = listAllFile(strDir, false);
		if (a != null && a.length > 0) {
			for (int i = 0; i < a.length; i++) {
				a[i] = dirName + a[i];
			}
		}
		return a;
	}

	/**
	 * 列表所有文件
	 * 
	 * @param strDir
	 * @param extName
	 * @return string[]
	 */
	public static String[] listAllFile(String strDir, String extName,
			boolean isFull) {
		List lDir = new ArrayList();
		List lFile = new ArrayList();
		String path = null;
		try {
//				lDir.add("/");
			lDir.add(File.separator);
			while (lDir.size() != 0) {
				path = (String) lDir.get(0);
				lDir.remove(0);
				File file = new File(strDir + path);
				String[] dirs = file.list(new FileNameFilterImpl(true, null));
				if (dirs != null) {
					for (int i = 0; i < dirs.length; i++) {
//							lDir.add(path + dirs[i] + "/");
						lDir.add(path + dirs[i] + File.separator);
					}
				}
				String[] files = file.list(new FileNameFilterImpl(false,
						extName));
				if (files != null) {
					if (isFull) {
						for (int i = 0; i < files.length; i++) {
							lFile.add(strDir + path + files[i]);
						}
					} else {
						for (int i = 0; i < files.length; i++) {
							lFile.add(path + files[i]);
						}
					}
				}
			}
		} catch (Exception e) {
			log.error("获取文件列表失败", e);
		}
		String[] file = new String[lFile.size()];
		for (int i = 0; i < lFile.size(); i++) {
			file[i] = (String) lFile.get(i);
		}
		return file;
	}

	/**
	 * 获取所有文件和文件夹
	 * 
	 * @param strDir
	 * @param extName 文件扩展名，如果不进行过滤extName=""
	 * @param isFull
	 *            包含子目录
	 * @param isContainDir
	 *            FileHelper.DIR；FileHelper.DIR_FILE；FileHelper.FILE
	 * @since v2.0
	 * @return
	 */
	public static String[] listAllFile(String strDir, String extName,
			boolean isFull, int isContainDir) {
		List<String> lDir = new ArrayList<String>();
		List<String> allDir = new ArrayList<String>();
		List<String> lFile = new ArrayList<String>();
		String path = null;
		try {
//				lDir.add("/");
			lDir.add(File.separator);
			while (lDir.size() != 0) {
				path = (String) lDir.get(0);
				lDir.remove(0);
				File file = new File(strDir + path);
				String[] dirs = file.list(new FileNameFilterImpl(true, null));
				if (dirs != null) {
					for (int i = 0; i < dirs.length; i++) {
//							lDir.add(path + dirs[i] + "/");
//							allDir.add(path + dirs[i] + "/");
						lDir.add(path + dirs[i] + File.separator);
						allDir.add(path + dirs[i] + File.separator);
					}
				}
				String[] files = file.list(new FileNameFilterImpl(false,
						extName));
				if (files != null) {
					if (isFull) {
						for (int i = 0; i < files.length; i++) {
							lFile.add(strDir + path + files[i]);
						}
					} else {
						for (int i = 0; i < files.length; i++) {
							lFile.add(path + files[i]);
						}
					}
				}
			}
		} catch (Exception e) {
			log.error("获取文件列表失败", e);
		}

		if (isContainDir == FILE) {
			int s = lFile.size();// +allDir.size();
			String[] dirs = new String[s];
			System.arraycopy(lFile.toArray(), 0, dirs, 0, lFile.size());
			return dirs;
		} else if (isContainDir == DIR) {
			int s = allDir.size();
			String[] dirs = new String[s];
			System.arraycopy(allDir.toArray(), 0, dirs, 0, allDir.size());
			return dirs;
		} else {
			int s = lFile.size() + allDir.size();
			String[] dirs = new String[s];
			System.arraycopy(lFile.toArray(), 0, dirs, 0, lFile.size());
			System.arraycopy(allDir.toArray(), 0, dirs, lFile.size(),
					allDir.size());
			return dirs;
		}
	}

	/**
	 * 获取文件名后缀 param fileName 文件名 return fileSuffix 文件名后缀 throws Exception
	 */
	public String getFileSuffix(String fileName) throws Exception {
		String fileSuffix;
		try {
			int index = fileName.lastIndexOf(".");
			fileSuffix = fileName.substring(index);
		} catch (Exception e) {
			throw new ZException("获取文件名后缀错误", e);
		}
		return fileSuffix;
	}

	/**
	 * 创建目录
	 * 
	 * @param dir
	 */
	public boolean makeDir(String dir) throws Exception {
		boolean flag = false;
		try {
			File file = new File(dir);
			flag = file.mkdir();
		} catch (Exception e) {
			throw new ZException("创建目录失败", e);
		}
		return flag;
	}

	/***************************************/
	/**
	 * /** 内嵌类fileNameFilterImpl.class /** /
	 ***************************************/
	static class FileNameFilterImpl implements FilenameFilter {
		private boolean isDir = false;
		private String extName = null;

		/**
		 * 构造函数
		 */
		public FileNameFilterImpl(boolean dir, String extName) {
			isDir = dir;
			this.extName = extName;
		}

		/**
		 * @param dir
		 * @param name
		 */
		public boolean accept(File dir, String name) {
			boolean m_ret = true;
			File m_file = new File(dir.getPath() + File.separator + name);
			if (isDir) {
				m_ret = m_file.isDirectory();
			} else {
				m_ret = m_file.isFile();
				if (m_ret == true && this.extName != null) {
					name = name.toLowerCase();
					this.extName = this.extName.toLowerCase();
					m_ret = name.endsWith(this.extName);
				}
			}
			return m_ret;
		}

	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param dir
	 * @param fileName
	 * @return
	 */
	public static boolean isExist(String dir, String fileNamePreFix) {
		boolean flag = false;
		String[] files = listAllFile(dir, false);
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].startsWith(File.separator + fileNamePreFix)) {
					flag = true;
					break;
				}
			}
		}
		return flag;
	}
	public static boolean isExist(String fileName){
		File f = new File(fileName);
		return f.exists();
	}
	/**
	 * 复制文件
	 * 
	 * @param srcName
	 *            源文件名
	 * @param destName
	 *            目标文件名
	 */
	public static void copy(String srcName, String destName)
			throws ZException {
		InputStream is = null;
		OutputStream os = null;
		byte[] buf = null;
		try {
			buf = new byte[8192];
			is = new FileInputStream(new File(srcName));
			os = new FileOutputStream(new File(destName));
			int len;
			while ((len = is.read(buf)) != -1) {
				os.write(buf, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ZException("拷贝文件失败", e);
		} finally {
			try {
				if (os != null) {
					os.close();
					os = null;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				if (is != null) {
					is.close();
					is = null;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	/**
	 * 复制文件或文件目录,自动判断文件夹还是文件。
	 * 
	 * @param srcName
	 *            源文件名（源文件名为目录时，不复制其中的文件）
	 * @param destName
	 *            目标文件名
	 */
	public static void copyx(String srcName, String destName)
			throws ZException {
		InputStream is = null;
		OutputStream os = null;
		byte[] buf = null;
		try {
			File src = new File(srcName);
			// 如果复制的是一个目录名，该目录不存在时,生成对应的目录
			if (src.isDirectory()) {
				File f = new File(destName);
				if (!f.exists()) {
					f.mkdirs();
				}
			} else {
				createFilePath(destName);
				buf = new byte[8192];
				is = new FileInputStream(new File(srcName));
				os = new FileOutputStream(new File(destName));
				int len;
				while ((len = is.read(buf)) != -1) {
					os.write(buf, 0, len);
				}
			}
		} catch (Exception e) {
			throw new ZException("拷贝文件失败", e);
		} finally {
			try {
				if (os != null) {
					os.close();
					os = null;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				if (is != null) {
					is.close();
					is = null;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	/**
	 * 删除指定文件或文件夹
	 * 
	 * @param _FileOrDirName
	 * @param _isDeleteSelf
	 * @throws java.lang.Exception
	 */
	public static void deleteFile(String _FileOrDirName, boolean _isDeleteSelf)
			throws Exception {
		try {
			// 获取文件对象
			java.io.File fFile = new java.io.File(_FileOrDirName);

			if (fFile.exists()) {
				// 存在
				if (!fFile.isDirectory()) {
					// 删除文件
					fFile.delete();
				} else {
					// 递归删除里面的文件和文件夹
					String[] strChildFileName = fFile.list();
					if (strChildFileName != null) {
						for (int i = 0; i < strChildFileName.length; i++) {
							// 递归删除
							deleteFile(_FileOrDirName + java.io.File.separator
									+ strChildFileName[i], true);
						}
					}

					// 删除目录自身
					if (_isDeleteSelf) {
						fFile.delete();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}

	/**
	 * 删除指定文件
	 * 
	 * @param fileName
	 */
	public static void deleteFile(String fileName) {
		File file = new File(fileName);
		file.delete();
	}

	/**
	 * 删除指定文件夹的文件和子文件夹
	 * 
	 * @param dirpath
	 *            文件夹路径
	 * @param day
	 *            指定的天数(day=0 表示删除目录中的所有文件和文件夹）
	 * @return i 删除的文件和文件夹个数
	 */
	public static void deleteFileAndDirctory(String dirpath, int day,
			boolean _isDeleteSelf) {
		long now = System.currentTimeMillis();
		long lday = day * 24 * 3600 * 1000;
		try {
			// 获取文件对象
			java.io.File fFile = new java.io.File(dirpath);

			if (fFile.exists()) {
				// 存在
				if (!fFile.isDirectory()) {
					// 删除文件
					System.out.println(fFile.lastModified());
					if (now - fFile.lastModified() > lday)
						fFile.delete();
				} else {
					// 递归删除里面的文件和文件夹
					String[] strChildFileName = fFile.list();
					if (strChildFileName != null) {
						for (int i = 0; i < strChildFileName.length; i++) {
							// 递归删除
							deleteFileAndDirctory(dirpath
									+ java.io.File.separator
									+ strChildFileName[i], day, true);
						}
					}
					// 删除目录自身
					if (_isDeleteSelf) {
						fFile.delete();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}

	/**
	 * 删除指定文件夹内1天前的文件和文件夹
	 * 
	 * @param dirpath
	 * @return
	 */
	public static void deleteFileBeforeToday(String dirpath) {
		deleteFileAndDirctory(dirpath, 1, false);
	}

	public static void main(String[] args) throws Exception {
		FileUtil.createFilePath("s:\\abc\\abc.txt");
	}

	/**
	 * 拷贝文件夹
	 * 
	 * @param src
	 *            源路径
	 * @param dest
	 *            目标路径
	 * @param isSubDir
	 *            是否拷贝子目录
	 * @since v2.0
	 */
	public static void copyDir(String src, String dest, boolean isSubDir) {
		try {
			if (src == null) {
				throw new IOException("源路径不存在");
			}
			if (dest == null) {
				throw new IOException("目标路径不能为null");
			}
			// 创建目标目录
			new File(dest).mkdirs();
			File file = new File(src);
			File[] dirs = file.listFiles();
			for (int i = 0; i < dirs.length; i++) {
				File tmp = dirs[i];
				if (tmp.isDirectory()) {
					String dirName = tmp.getName();
					String src1 = tmp.getAbsolutePath();
					String dest1 = dest + File.separator + dirName;
					new File(dest1).mkdirs();
					// 递归
					if (isSubDir) {
						copyDir(src1, dest1, isSubDir);
					}
				} else if (tmp.isFile()) {
					copy(tmp.getAbsolutePath(),
							dest + File.separator + tmp.getName());
				}
			}
		} catch (Exception e) {
			log.error("文件夹拷贝失败", e);
		}
	}

	/**
	 * 将文件读取为字符串
	 * 
	 * @param fileName
	 * @param charset
	 * @return
	 */
	public static String readFile2Str(String fileName, String charset) {
		String rs = "";
		StringBuilder sb = new StringBuilder();
		FileReader fr = null;
		BufferedReader br = null;
		char[] cbuf = new char[8096];
		try {
			File f = new File(fileName);
			fr = new FileReader(f);
			br = new BufferedReader(fr);
			int i = 0;
			while ((i = br.read(cbuf, 0, 8096)) != -1) {
				sb.append(cbuf, 0, i);
			}
			cbuf = null;
			if (br != null) {
				br.close();
				br = null;
			}
			if (fr != null) {
				fr.close();
				fr = null;
			}
		} catch (Exception e) {
			log.error("读取文件发生错误", e);
		} finally {
			cbuf = null;
			if (br != null) {
				try {
					br.close();
				} catch (Exception e2) {

				}
				br = null;
			}
			if (fr != null) {
				try {
					fr.close();
				} catch (Exception e2) {
				}
				fr = null;
			}
		}
		rs = sb.toString();
		sb.delete(0, sb.length());
		sb = null;
		return rs;
	}

	/**
	 * 将字符串写入文件
	 * 
	 * @param fileName
	 * @param charset
	 * @return
	 */
	public static void writeStr2File(String fileName, String charset,
			String content) {
		String rs = "";
		StringBuilder sb = new StringBuilder();
		BufferedWriter bw = null;
		OutputStreamWriter osw = null;
		FileOutputStream fos = null;
		try {
			File f = new File(fileName);
			fos = new FileOutputStream(f);
			osw = new OutputStreamWriter(fos, charset);
			bw = new BufferedWriter(osw);
			bw.write(content);
			bw.flush();
		} catch (Exception e) {
			log.error("写入文件发生错误", e);
		} finally {
			try {
				if (bw != null) {
					bw.close();
					bw = null;
				}
			} catch (Exception e2) {
			}
			try {
				if (osw != null) {
					osw.close();
					osw = null;
				}
			} catch (Exception e2) {
			}
			try {
				if (fos != null) {
					fos.close();
					fos = null;
				}
			} catch (Exception e2) {
			}
		}
	}

	/**
	 * 在文件末尾增加内容
	 * 
	 * @param fileName
	 * @param content
	 *            字符串内容
	 */
	public static void append(String fileName, String content) {
		File f = new File(fileName);
		FileWriter fw = null;
		try {
			fw = new FileWriter(f, true);
			fw.append(content);
			fw.close();
			fw = null;
		} catch (Exception e) {
			log.error("追加文件失败", e);
		} finally {
			if (fw != null) {
				try {
					fw.close();
					fw = null;
				} catch (Exception e2) {
				}
			}
		}
	}
	/**
	 * nio方式文件拷贝
	 * @param src  源文件路径
	 * @param dest 目标文件路径
	 */
	public static void nioCopy(String src,String dest){
        File s = new File(src);
        File d = new File(dest);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel sourceCh = null;
        FileChannel destCh = null;
        try {
        	fis = new FileInputStream(s);
        	fos = new FileOutputStream(dest);
        	sourceCh = fis.getChannel();
        	destCh = fos.getChannel();
        	long off = 0l;
        	long maxlen = 0l;
        	long srcLen = sourceCh.size();
        	long l = 0;
        	if(srcLen>Integer.MAX_VALUE){
        		maxlen = Integer.MAX_VALUE;
        	}else
        	{
        		maxlen = srcLen;
        	}
        	while((l=destCh.transferFrom(sourceCh, off, maxlen))!=-1)
        	{
        		off+=l;
        		if(off<srcLen){
        			if(srcLen-off<Integer.MAX_VALUE){
        				maxlen = srcLen-off;
        			}
        		}else{
        			break;
        		}
        	}
        	sourceCh.close();
        	sourceCh = null;
        	destCh.close();
        	destCh = null;
        	fis.close();
        	fis = null;
        	fos.close();
        	fos = null;
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
        catch (Exception e) {
        	e.printStackTrace();
		}finally{
			try {
				if(sourceCh!=null){
				sourceCh.close();
	        	sourceCh = null;}
	        	if(destCh!=null){
	        	destCh.close();
	        	destCh = null;}
	        	if(fis!=null){fis.close();
	        	fis = null;}if(fos!=null){
	        	fos.close();
	        	fos = null;}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

	}
	/**
	 * 内存映射方式文件拷贝
	 * @param src
	 * @param dest
	 */
	public static void mapCopy(String src,String dest){
		File s = new File(src);

        File d = new File(dest);

        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel sourceCh = null;
        FileChannel destCh = null;
        try {
        	fis = new FileInputStream(s);
        	fos = new FileOutputStream(dest);
        	sourceCh = fis.getChannel();
        	destCh = fos.getChannel();
        	long sLen = sourceCh.size();
        	long mapLen = 0L;
        	long off=0L;
        	if(sLen>Integer.MAX_VALUE){
        		mapLen = Integer.MAX_VALUE;
        	}else{
        		mapLen=sLen;
        	}
        	while(off<sLen){
	        	MappedByteBuffer mbb = sourceCh.map(FileChannel.MapMode.READ_ONLY, off, mapLen);
	        	destCh.write(mbb);
	        	off+=mapLen;
	        	if(sLen-off<mapLen){
	        		mapLen =sLen-off; 
	        	}
        	}
        	sourceCh.close();
        	sourceCh = null;
        	destCh.close();
        	destCh = null;
        	fis.close();
        	fis = null;
        	fos.close();
        	fos = null;
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
        catch (Exception e) {
        	e.printStackTrace();
		}finally{
			try {
				if(sourceCh!=null){
				sourceCh.close();
	        	sourceCh = null;}
	        	if(destCh!=null){
	        	destCh.close();
	        	destCh = null;}
	        	if(fis!=null){fis.close();
	        	fis = null;}if(fos!=null){
	        	fos.close();
	        	fos = null;}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	/**
	 * 获取文件crc32值
	 * @param filename
	 * @return
	 */
	public static String getCrc32(String filename){
		return getCrc32(new File(filename));
	}
	/**
	 * 获取文件crc32值
	 * @param filename
	 * @return
	 */
	public static String getCrc32(File file){
		FileInputStream fis=null;
		byte[] buf = new byte[102400];
		CRC32 crc = new CRC32();
		String code = null;
		try {
			crc.reset();
			fis = new FileInputStream(file);
			int i = 0;
			while((i=fis.read(buf,0,buf.length))!=-1){
				crc.update(buf,0,i);
			}
			fis.close();
			fis = null;
			code = Long.toString(crc.getValue());
			crc = null;
		} catch (Exception e) {
			log.error("生成文件crc32值失败",e);
		}
		finally{
			if(fis!=null){
				try {
					fis.close();
				} catch (Exception e2) {
				}
				fis=null;
			}
			if(crc!=null){
				crc= null;
			}
		}
		return code;
	}
	public static long getCrc32Long(String filename){
		return getCrc32Long(new File(filename));
	}
	public static long getCrc32Long(File file){
		FileInputStream fis=null;
		byte[] buf = new byte[102400];
		CRC32 crc = new CRC32();
		long code = 0l;
		try {
			crc.reset();
			fis = new FileInputStream(file);
			int i = 0;
			while((i=fis.read(buf,0,buf.length))!=-1){
				crc.update(buf,0,i);
			}
			fis.close();
			fis = null;
			code = crc.getValue();
			crc = null;
		} catch (Exception e) {
			log.error("生成文件crc32值失败",e);
		}
		finally{
			if(fis!=null){
				try {
					fis.close();
				} catch (Exception e2) {
				}
				fis=null;
			}
			if(crc!=null){
				crc= null;
			}
		}
		return code;
	}
	/**
	 * 读取文件到字符串
	 * @param fileName
	 * @return
	 */
	public static String readFile(String fileName){
		StringBuilder sb = new StringBuilder();
		char[] cbuf = new char[8192];
		FileReader fr = null;
		try {
			fr = new FileReader(fileName);
			int i = 0;
			while((i=fr.read(cbuf,0,cbuf.length))!=-1){
				sb.append(cbuf,0,i);
			}
			if(fr!=null){
				fr.close();
				fr = null;
			}
		} catch (Exception e) {
			log.error("读取文件失败",e);
		}finally{
			try {
				if(fr!=null){
					fr.close();
					fr = null;
				}
			} catch (Exception e2) {
			}
		}
		String str = sb.toString();
		sb.delete(0, sb.length());
		return str;
	}
	/**
	 * 文件夹拷贝
	 * @param srcFolder 数据源文件夹
	 * @param destFolder 目标文件夹
	 * @param prex 忽略掉的前缀
	 * @see
	 * srcFolder="d:/mitsmp/temp/abcdefag/";
	 * destFolder="d:/mitsmp/pages/rongh";
	 * prex="d:/mitsmp/temp/a";
	 */
	public static void copyFolder(String srcFolder,String destFolder){
		srcFolder = srcFolder.replaceAll("//", "/");
		String[] files=listAllFile(srcFolder, true);
		for(int i=0;i<files.length;i++){
			String src= files[i];
			String dest=destFolder+src.substring(srcFolder.length());
			try {
				validateFilePath(dest);
				copy(src,dest);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	/**
	   * 创建文件夹
	   * @param path
	   */
	  public static void mkdirs(String path){
		  File f = new File(path);
		  if(f.exists())
		  {
			  if(!f.isDirectory())
			  {
				f.mkdirs();
			  }
		  }
		  else
		  f.mkdirs();
	  }
	  /**
	   * 移动文件
	   * @param src
	   * @param des
	   */
	  public static void mv(String src,String des){
		  File f = new File(src);
		  f.renameTo(new File(des));
	  }
	  /**
	   * 创建文本类型文件
	   * @param content
	   * @param filePath
	   * @param charset
	 * @throws ZException 
	   */
	  public static void crFile(String content,String filePath,String charset) throws ZException{
		  File f = new File(filePath);
		  FileOutputStream fos = null;
		  try {
			fos = new FileOutputStream(f);
			fos.write(content.getBytes(charset));
			fos.flush();
		} catch (Exception e) {
			throw new ZException("创建文件失败",e);
		}
		finally{
			try {
				fos.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	  }
	  
	  /**
	   * 写入文件
	   * @param fileName
	   * @param content
	   * @param fileEncoding
	   * @throws ZException
	   */
	  public static void str2File(String fileName,String content,String fileEncoding) throws ZException
	  {
		  FileOutputStream fos =null;
		  OutputStreamWriter osw = null;
		  try {
			fos = new FileOutputStream(new File(fileName));
			osw = new OutputStreamWriter(fos,fileEncoding);
			osw.write(content);
			osw.flush();
		} catch(IOException e){
			throw new ZException("文件操作错误",e);
		}
		catch (Exception e) {
			throw new ZException("未知异常",e);
		}
		finally
		{
			try {
				if(osw!=null){
					osw.close();
					osw=null;
				}
			} catch (Exception e2) {
			}
			try {
				if(fos!=null){
					fos.close();
					fos=null;
				}
			} catch (Exception e2) {
			}
		}
	  }
}

